package com.icss.th.common.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import com.icss.th.common.Constants;
import com.icss.th.common.config.SystemConfig;

/**
 * 数据连接类
 * @author CSI-peijn
 *
 */
public class DBUtil 
{	
	private static DataSource MYSQL_DS = getDataSource(SystemConfig.JNDI_MYSQL);
	
	private static DataSource SQLSERVER_DS = getDataSource(SystemConfig.JNDI_SQLSERVER);
	
	/**
	 * 得到系统默认数据连接
	 * @return
	 */
	public static Connection getConn()
	{
		return getConn(Constants.DB_TYPE.MYSQL);
	}
	
	/**
	 * 通过数据源类型得到连接
	 * @param type
	 * @return
	 */
	public static Connection getConn(String type)
	{
		Connection conn = null;
		
		try
		{
			if (Constants.DB_TYPE.MYSQL.equals(type) && MYSQL_DS != null)
			{
				conn = MYSQL_DS.getConnection();
			}
			else if (Constants.DB_TYPE.SQLSERVER.equals(type) && SQLSERVER_DS != null)
			{
				conn = SQLSERVER_DS.getConnection();
			}
		}
		catch (SQLException e)
		{
			e.printStackTrace();
		}
		
		return conn;
	}
	
	/**
	 * 根据jndi得到数据连接datasource
	 * @param jndiName
	 * @return
	 */
	private static DataSource getDataSource(String jndiName) 
	{
		DataSource ds = null;
		Context ctx = null;
		
		try
		{
			try 
			{
				ctx = new InitialContext();
				ds = (DataSource)ctx.lookup(jndiName);
			} 
			finally
			{
				if (ctx != null)
				{
					ctx.close();
				}
			}
		}
		catch (NamingException e) 
		{
			e.printStackTrace();
		}
        
        return ds;
	}
	
	
}
